﻿using System;
using System.Threading;
using System.Threading.Tasks;
using TabbedTemplate.Models;
using Xamarin.Essentials;

namespace TabbedTemplate.Services
{
    public class GeoLocationService : IGeoLocationService
    {
        public async Task<Position> GetLocationAsync()
        {
            CancellationTokenSource cts;
            Position positionToReturn = null;
            try
            {
                var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
                cts = new CancellationTokenSource();
                var location = await Geolocation.GetLocationAsync(request, cts.Token);

                if (location != null)
                {
                    return positionToReturn = new Position
                    {
                        Longitude = location.Longitude,
                        Latitude = location.Latitude
                    };
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                return null;
                // Handle not supported on device exception
            }
            catch (FeatureNotEnabledException fneEx)
            {
                return null;
                // Handle not enabled on device exception
            }
            catch (PermissionException pEx)
            {
                return null;
                // Handle permission exception
            }
            catch (Exception ex)
            {
                return null;
                // Unable to get location
            }
            return positionToReturn = new Position
            {
                Latitude = double.MaxValue,
                Longitude = double.MaxValue
            };
        }
    }

}
